package tw.com.softleader.steven;

import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.net.URL;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.swing.JFrame;

import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;

public class Execute {
	
	private static final String INDEX_PAGE = "http://lifebox.twbbs.org/Line/index";
	
	private static final String SEARCH_URL = "http://lifebox.twbbs.org/Line/index?Search=free&Start=";
	
	private static final String CHECK_TOKEN = "http://lifebox.twbbs.org/Line/checktoken";
	
	public String[] getImageNo() {
		List<String> picNos = Lists.newArrayList();
		HttpClient client = new DefaultHttpClient();
		HttpGet request = new HttpGet(INDEX_PAGE);
		String responseContent = "";
		try {
			System.out.println("取得總頁數開始");
			HttpResponse response = client.execute(request);
			responseContent = EntityUtils.toString(response.getEntity());
			System.out.println("取得總頁數結束");
		} catch (Exception e) {
		}
		try {
			String totalPageString = Jsoup.parse(responseContent).getElementById("footer").select("ul").select("li").get(2).html().toString();
			int totalPage = 0;
			Matcher matcher = Pattern.compile("\\d+").matcher(totalPageString.split("/")[1]);
			if (matcher.find()) {
				totalPage = Integer.parseInt(matcher.group());
				System.out.println("總共 " + totalPage + " 頁");
				for (int i = 0; i < totalPage; i++) {
					System.out.println("取得第" + (i + 1) + "頁的圖片編號");
					request = new HttpGet(SEARCH_URL + (i * 10));
					try {
						HttpResponse response = client.execute(request);
						responseContent = EntityUtils.toString(response.getEntity());
					} catch (Exception e) {
					}
					Document doc = Jsoup.parse(responseContent);
					Elements liElements = doc.select("ul[data-role=listview]").select("li[data-icon=info]");
					for (Element li : liElements) {
						if (StringUtils.isNotEmpty(li.select("a[data-theme=d]").toString())) {
							System.out.println("有效圖片編號: " + li.select("h2").html().split(":")[1].trim());
							picNos.add(li.select("h2").html().split(":")[1].trim());
						}
					}
				}
				
			}
		} catch (Exception e) {
		}
		System.out.println("取得圖片編號: " + picNos);
		return Iterables.toArray(picNos, String.class);
	}
	
	public String doSubmit(String authKey, String accessToken, List<String> pics, int retry) {
		System.out.println("authKey: " + authKey);
		System.out.println("accessToken: " + accessToken);
		System.out.println("pics: " + pics);
		System.out.println("retry: " + retry);
		StringBuffer message = new StringBuffer();
		Command command = null;
		if (retry <= -1) {
			command = new InfiniteExecute();
		} else {
			command = new FiniteExecute(retry);
		}
		for (String picNo : pics) {
			message.append(command.execute(authKey, accessToken, picNo));
		}
		return message.toString(); 
	}
	
	public String doCheckToken(String authKey, String accessToken) {
		System.out.println("authKey: " + authKey);
		System.out.println("accessToken: " + accessToken);
		StringBuffer message = new StringBuffer();
		HttpClient client = new DefaultHttpClient();
		HttpGet request = new HttpGet(CHECK_TOKEN + "?Authkey=" + StringUtils.trimToEmpty(authKey) + "&AccessToken=" + StringUtils.trimToEmpty(accessToken));
		String responseContent = "";
		try {
			System.out.println("驗證開始");
			HttpResponse response = client.execute(request);
			responseContent = EntityUtils.toString(response.getEntity());
			System.out.println("驗證結束");
		} catch (Exception e) {
		}
		message.append(Jsoup.parse(responseContent).select("p").get(3).text());
		return message.toString();
	}
	
	public String getAccessTokenFromDevice() {
		try {
			URL url = Execute.class.getResource("/iPhoneLineAccessTokenTool.exe");
			System.out.println("iPhoneLineAccessTokenTool.exe path: " + url.toString().replaceAll("file:/", ""));

			File root = new File("C:/");
			File tempIPhoneLineAccessTokenTool = new File(root, "iPhoneLineAccessTokenTool.exe");
			File tempSystemDataSQLite = new File(root, "System.Data.SQLite.dll");
			
			try (BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(tempIPhoneLineAccessTokenTool))) {
				try (BufferedInputStream in = new BufferedInputStream(Execute.class.getResourceAsStream("/iPhoneLineAccessTokenTool.exe"))) {
					byte[] buffer = new byte[2048];
					while (in.read(buffer) != -1) {
						out.write(buffer);
					}
				} catch (Exception e) {
					
				}
			} catch (Exception e) {
				
			}
			
			try (BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(tempSystemDataSQLite))) {
				try (BufferedInputStream in = new BufferedInputStream(Execute.class.getResourceAsStream("/System.Data.SQLite.dll"))) {
					byte[] buffer = new byte[2048];
					while (in.read(buffer) != -1) {
						out.write(buffer);
					}
				} catch (Exception e) {
					
				}
			} catch (Exception e) {
				
			}
			
			// execute process
			JFrame frame = new JFrame("Use Clipboard");
			Process process = Runtime.getRuntime().exec(tempIPhoneLineAccessTokenTool.getAbsolutePath());
			Thread.sleep(20000);  // wait for process
			process.destroy();    // kill process
			
			// get clipboard data
			final Clipboard clipboard = frame.getToolkit().getSystemClipboard();
			Transferable clipData = clipboard.getContents(clipboard);
			String accessToken = (String) (clipData.getTransferData(DataFlavor.stringFlavor));
			System.out.println("access token: " + accessToken);
			
			tempIPhoneLineAccessTokenTool.delete();
			tempSystemDataSQLite.delete();
			
			return accessToken;
		} catch (Exception e) {
			return "";
		}
	}

}
